from CvPythonExtensions import *

import GerikSpells
import GerikSpellsUtils
from GerikSpells import GerikSpellBase
from GSGroupPolicies import GSAll as GSGroup
from GSHandlerPolicies import GSImmediate as GSHandler
from GSResultsPolicies import GSBuild as GSResults

gc = CyGlobalContext()
localtext = CyTranslator()

# Tuple of techs required.
techsNeeded = ( gc.getInfoTypeForString("TECH_BIOLOGY"), )

# Tuple of unit classes that can plant a forest.
unitClassTypeNeeded = ( gc.getInfoTypeForString("UNITCLASS_WORKER"), )

# Other constants
FOREST_TYPE = gc.getInfoTypeForString("FEATURE_FOREST")
FOREST_BUILD_TIME = 600

class PlantForest(GerikSpellBase, GSGroup, GSHandler, GSResults):
    def __init__(self):
        GerikSpellBase.__init__(self)
        GSGroup.__init__(self)
        GSHandler.__init__(self)
        GSResults.__init__(self)
        self.setBuildTime(FOREST_BUILD_TIME)

    def canUnitCast(self, pCastingUnit, pPlot, bVisible):
        # Test if the unit is a worker.
        if not pCastingUnit.getUnitClassType() in unitClassTypeNeeded:
            return False

        return True
        
    def canGroupCast(self, pCastingGroup, pPlot, bVisible):
        # Check if the player has the techs required.
        # Because when a selection group is first formed, it's owner is not yet set before
        # the call is made to check for different actions, it's safer to check the head
        # unit when determining owner or team.
        pTeam = gc.getTeam(pCastingGroup.getHeadUnit().getTeam())
        for tech in techsNeeded:
            if not pTeam.isHasTech(tech):
                return False

        # Test that there are no other features already on the plot.
        if pPlot.getFeatureType() != -1:
            return False

        # Test of the terrain type is valid for a forest.
        if not gc.getFeatureInfo(FOREST_TYPE).isTerrain(pPlot.getTerrainType()):
            return False

        return GSGroup.canGroupCast(self, pCastingGroup, pPlot, bVisible)

    def continueSpellResults(self, pCastingGroup, pTargetInfo):
        pCastingGroup.plot().setFeatureType(FOREST_TYPE, -1)

    def getHelpText(self, pGroup, pPlot):
        # The forest may already be finished.
        if (pPlot.getFeatureType() != FOREST_TYPE):
            iBuildTurnsLeft = self.getBuildTurnsLeftWithHelp(pPlot, pGroup)
            return "%s" % localtext.getText("TXT_KEY_PLANT_FOREST_HELP", (iBuildTurnsLeft,))
        else:
            return ""

    def getUnitHelpText(self, pUnit):
        # The forest may already be finished.
        if (pUnit.plot().getFeatureType() != FOREST_TYPE):
            iBuildTurnsLeft = self.getBuildTurnsLeft(pUnit.plot())
            return localtext.getText("TXT_KEY_PLANT_FOREST_HELP", (iBuildTurnsLeft,))
        else:
            return ""
